package org.jypj.dev.controller;

import com.alibaba.fastjson.JSONObject;
import org.jypj.dev.constant.JpushConstant;
import org.jypj.dev.dao.IUserDao;
import org.jypj.dev.model.*;
import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.service.INoticeMessageService;
import org.jypj.dev.util.*;
import org.jypj.dev.vo.hxVo.PushObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ChenYu on 2017-05-10.
 */
@Controller
@RequestMapping(value = "messageController")
public class MessageController extends BaseController {

    @Resource
    private IUserDao userDao;

    @Resource
    private ICodeDataService codeDataService;

    @Resource
    private INoticeMessageService noticeMessageService;


    /**
     * 跳转到消息主页
     *
     * @return
     */
    @RequestMapping(value = "toMsgNotice.action")
    public String toMsgNotice() {

        return "back/message/message_notice";
    }

    /**
     * 查询用户
     *
     * @return
     */
    @RequestMapping(value = "toUserList.action")
    public String toUserList(HttpServletRequest request) {
        List<CodeData> bmgls = codeDataService.selectAllByCode("bmgl");
        request.setAttribute("codeDatas", bmgls);
        return "back/message/message_user_list";
    }

    /**
     * 查询用户
     *
     * @return
     */
    @RequestMapping(value = "toDepList.action")
    public String toDepList(HttpServletRequest request) {

        return "back/message/message_dep_list";
    }

    /**
     * 查询所有部门
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllDep.action")
    public Map<String, Object> selectAllDep() {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            List<CodeData> bmgl = codeDataService.selectAllByCode("bmgl");
            dataMap.put("datas", bmgl);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询用户列表
     *
     * @return
     */
    @RequestMapping(value = "selectOnePageUser.action")
    @ResponseBody
    public Page selectUserList(Page page, String depNum, String searchCode) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("searchCode", searchCode);
        queryMap.put("depNum", depNum);
        List<User> users = userDao.selectOnePageByMap2(page, queryMap);
        page.setResult(users);
        return page;
    }

    /**
     * 查询所有通知消息
     *
     * @return
     */
    @RequestMapping(value = "selectAllNoticeMsg.action")
    @ResponseBody
    public Map<String, Object> selectAllNoticeMsg() {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            String file_server_url = PropertyUtil.getProperties("file_server_url");
            List<NoticeMessage> noticeMessages = noticeMessageService.selectAllByMap(queryMap);
            for (NoticeMessage noticeMessage : noticeMessages) {
                noticeMessage.setCoverPicAllUrl(StringUtil.isEmpty(noticeMessage.getCoverPic()) ? "" : file_server_url + noticeMessage.getCoverPic());
            }
            dataMap.put("tableData", noticeMessages);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 上传文件
     *
     * @param imgFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uploadImage")
    public Map<String, Object> uploadFile(MultipartFile imgFile, String type) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        String msg = "图片上传成功";
        String realPath = "";
        try {
            JSONObject jo = new JSONObject();
            if (imgFile != null) {
                if ("1".equals(type)) {
                    realPath = "/messageImage";
                } else {
                    realPath = "/messageFile";
                }
                String upload = FileUtil.upload(realPath, imgFile);
                jo.put("src", upload);
                jo.put("title", imgFile.getOriginalFilename());
            }
            dataMap.put("data", jo);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        dataMap.put("msg", msg);
        return dataMap;
    }

    /**
     * 保存或者更新
     *
     * @param noticeMessage
     * @return
     */
    @RequestMapping(value = "saveOrUpdate.action")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(NoticeMessage noticeMessage, HttpSession session) {
        Map<String, Object> dataMap = new HashMap<>();
        String todayString = DateUtils.getTodayString("yyyy-MM-dd HH:mm:ss");
        User user = (User) session.getAttribute("user");
        int code = 0;
        try {
            if (StringUtil.isEmpty(noticeMessage.getContent()) || noticeMessage.getContent().length() < 50) {
                code = -2;
            } else {
                String userName = "";
                if (null != user) {
                    userName = user.getUsername();
                }
                noticeMessage.setModifyUser(userName);
                if (StringUtil.isEmpty(noticeMessage.getSubContent())) {
                    noticeMessage.setSubContent(noticeMessage.getContent().substring(0, 64));
                }
                noticeMessage.setModifyTime(todayString);
                if (StringUtil.isNotEmpty(noticeMessage.getId())) {
                    //更新
                    noticeMessageService.updateNoticeMessage(noticeMessage);
                } else {
                    //保存
                    noticeMessage.setCreateTime(todayString);
                    noticeMessage.setCreateUser(userName);
                    noticeMessageService.saveNoticeMessage(noticeMessage);
                }
                dataMap.put("noticeMessage", noticeMessage);
            }

        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 发送消息 有可能是立即发送，有可能是保存后发送
     *
     * @param noticeMessage
     * @param session
     * @return
     */
    @RequestMapping(value = "sendMessage.action")
    @ResponseBody
    public Map<String, Object> sendMessage(NoticeMessage noticeMessage, HttpSession session) {
        Map<String, Object> dataMap = new HashMap<>();
        String todayString = DateUtils.getTodayString("yyyy-MM-dd HH:mm:ss");
        User user = (User) session.getAttribute("user");
        int code = 0;
        try {
            if (StringUtil.isEmpty(noticeMessage.getContent()) || noticeMessage.getContent().length() < 50) {
                code = -2;
            } else {
                String userName = "";
                if (null != user) {
                    userName = user.getUsername();
                }
                noticeMessage.setModifyUser(userName);
                if (StringUtil.isEmpty(noticeMessage.getSubContent())) {
                    noticeMessage.setSubContent(noticeMessage.getContent().substring(0, 50));
                }
                noticeMessage.setModifyTime(todayString);
                noticeMessage.setSendTime(todayString);
                noticeMessage.setSendUserName(user.getUsername());
                noticeMessage.setSendUserNum(user.getUserNum());
                noticeMessage.setStatus(1);
                if (StringUtil.isNotEmpty(noticeMessage.getId())) {
                    //更新
                    noticeMessageService.updateNoticeMessage(noticeMessage);
                } else {
                    //保存
                    noticeMessage.setCreateTime(todayString);
                    noticeMessage.setCreateUser(userName);
                    noticeMessageService.saveNoticeMessage(noticeMessage);
                }
                dataMap.put("noticeMessage", noticeMessage);

                //推送
                NoticeMessage noticeMessage1 = noticeMessage.deepClone();
                noticeMessage1.setCoverPic(noticeMessage1.getCoverPic());
                noticeMessage1.setContent("");
                noticeMessage1.setContentHtml("/webApp/showMsg/" + noticeMessage1.getId());

                PushObject pushObject = new PushObject();
                pushObject.setPushTime(todayString);
                pushObject.setPushTitle(noticeMessage1.getTitle());
                pushObject.setPushContent(noticeMessage1.getSubContent());
                pushObject.setPushType(JpushConstant.NOTICE_MESSAGE);
                pushObject.setPushValue(noticeMessage1);
                System.out.println(pushObject);
                JpushClientUtil.sendSelfMessageToAllAndroid(pushObject.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 按ID删除资讯
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteById.action")
    public Map<String, Object> deleteById(String id) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            noticeMessageService.deleteNoticeMessageById(id);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

}
